package com.sicnustray.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sicnustray.entity.Menu;
import com.sicnustray.entity.Role;
import com.sicnustray.entity.RoleMenu;
import com.sicnustray.mapper.RoleMapper;
import com.sicnustray.mapper.RoleMenuMapper;
import com.sicnustray.service.IMenuService;
import com.sicnustray.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yl
 * @since 2022-11-09
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private
    IMenuService menuService;

    @Transactional
    @Override
    public void setRoleMenu(Integer roleId, List<Integer> menuIds) {
        QueryWrapper<RoleMenu> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId);
        roleMenuMapper.delete(queryWrapper);
        if(!menuIds.contains(2)){
            menuIds.add(2);
        }
        List<Integer> menuIdsCopy= CollUtil.newArrayList(menuIds);
        for(Integer menuId : menuIds){
            Menu menu= menuService.getById(menuId);
            if(menu.getPid()!=null&&!menuIdsCopy.contains(menu.getPid())){
                RoleMenu roleMenu=new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menu.getPid());
                roleMenuMapper.insert(roleMenu);
                menuIdsCopy.add(menu.getPid());
            }
            RoleMenu roleMenu=new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuMapper.insert(roleMenu);
        }

    }

    @Override
    public List<Integer> getRoleMenu(Integer roleId) {
        return roleMenuMapper.selectByRoleId(roleId);
    }

    @Override
    public void deleteMenuById(Integer id) {

        QueryWrapper<RoleMenu> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("role_id",id);
        roleMenuMapper.delete(queryWrapper);
    }


}
